﻿
using WebViewControl.Contracts;

namespace WebViewControl.Views
{
    /// <summary>
    /// WebviewWindow.xaml 的交互逻辑
    /// </summary>
    public partial class WebviewWindow : UserControl
    {
        private readonly IWebViewManager _webViewManager;
        public WebviewWindow(IWebViewManager webViewManager)
        {
            InitializeComponent();
            // 在视图加载后添加WebView2控件
            Loaded += WebViewer_Loaded;
            Unloaded += WebViewHost_Unloaded;
            _webViewManager = webViewManager;
        }
        private async void WebViewer_Loaded(object sender, RoutedEventArgs e)
        {
            var webView = await _webViewManager.CreateOrGetAsync("viewer1");
            //Container.Children.Add(webView);
            webView.HorizontalAlignment = HorizontalAlignment.Stretch;
            webView.VerticalAlignment = VerticalAlignment.Stretch;
            webView.Margin = new Thickness(0);
            webView.SetValue(Grid.RowProperty, 0);
            if(WebContainer.Children.Count == 0)
            {
                WebContainer.Children.Add(webView);
            }
            
            _webViewManager.WebViewInitialized += (s, key) =>
            {
                if (key == "viewer1")
                {
                    // 初始化成功后的逻辑，如导航、设置内容等
                    // 执行导航或其他逻辑
                    if (this.DataContext is WebviewViewModel vm)
                    {
                        vm.SET_WEBViewNAME("viewer1");
                    }
                    this.LoadingIndicator.Visibility = Visibility.Hidden;
                    _webViewManager.NavigateAsync("viewer1", "C:\\Users\\haonan.fu\\Desktop\\新建文件夹 (2)\\welcome3.html");
                   
                }
            };
            await _webViewManager.InitializeAsync("viewer1");

            
            
        }
        private async void WebViewHost_Loaded(object sender, RoutedEventArgs e)
        {
            // 确保WebView2添加到可视化树中
     
        } 
  
        private void WebViewHost_Unloaded(object sender, RoutedEventArgs e)
        {
            
            // 防止控件被移除，但保留引用
            //WebViewContainer.Content = null;
        }
    }
}
